import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;

public class SongDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JPanel panel1;
    private JTextField textField2;
    private JTextField textField3;
    private JTextField textField1;
    private JButton addButton;
    private JPanel textLayout;
    private JPanel boxLayout;
    private ArrayList<TextElement> elements = new ArrayList<TextElement>();

    public SongDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object[] possibilities = {"verse", "chorus", "bridge"};
                String s = (String) JOptionPane.showInputDialog(
                        SongDialog.this,
                        "Виберіть елемент",
                        "Виберіть елемент",
                        JOptionPane.PLAIN_MESSAGE,
                        null,
                        possibilities,
                        "ham");
                //If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    addElement(s);
                }
            }
        });
        boxLayout = new JPanel();
        BoxLayout box = new BoxLayout(boxLayout,BoxLayout.PAGE_AXIS);
        boxLayout.setLayout(box);
        textLayout.add(boxLayout);

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void addElement(String s) {
        TextElement temp = new TextElement();
        elements.add(temp);
        temp.setElementType(s);
        boxLayout.add(temp.getRoot());
        contentPane.revalidate();
    }

    private void onOK() {
// add your code here
        try {
            saveData();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        dispose();
    }

    private void saveData() throws ParserConfigurationException, TransformerException {
        DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
        //Get the DOM Builder
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element root = doc.createElement("song");
        doc.appendChild(root);
        Element header = doc.createElement("header");
        String nameString = textField1.getText();
        String authorString = textField2.getText();
        String typeString = textField3.getText();
        if (nameString != null && !nameString.isEmpty()) {
            Element name = doc.createElement("name");
            name.appendChild(doc.createTextNode(nameString));
            header.appendChild(name);
        }
        if (authorString != null && !authorString.isEmpty()) {
            Element author = doc.createElement("author");
            author.appendChild(doc.createTextNode(authorString));
            header.appendChild(author);
        }
        if (typeString != null && !typeString.isEmpty()) {
            Element type = doc.createElement("genre");
            type.appendChild(doc.createTextNode(typeString));
            header.appendChild(type);
        }
        root.appendChild(header);
        Element body = doc.createElement("body");
        for (TextElement element : elements) {
            body.appendChild(element.getXml(doc));
        }
        root.appendChild(body);
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("file.xml"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }

    public static void main(String[] args) {
        SongDialog dialog = new SongDialog();
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }

    private void createUIComponents() {
        // TODO: place custom component creation code here
    }
}
